import paho.mqtt.client as mqtt
import sys
import time

HOST = "202.38.75.252"
PORT = 1883


# 消息发布
def publisher():
    client = mqtt.Client()
    # 建立连接
    client.connect(HOST, PORT, 60)

    while True:
        client.publish("testtopic", payload="Hello World", qos=0)
        time.sleep(1)


# 消息接收
def subscriber():
    # 连接成功回调
    def on_connect(client, userdata, flags, rc):
        print("Connected with result code " + str(rc))
        client.subscribe("testtopic/#")

    # 消息接收回调
    def on_message(client, userdata, msg):
        print(msg.topic + " " + str(msg.payload))

    client = mqtt.Client()
    # 建立连接
    client.connect(HOST, PORT, 60)
    # 指定回调函数
    client.on_connect = on_connect
    client.on_message = on_message
    client.loop_forever()


def main():
    t = sys.argv[1]
    if t == "publisher":
        publisher()
    elif t == "subscriber":
        subscriber()
    else:
        print("type must be publisher or subscriber.")


if __name__ == "__main__":
    main()
